<?php

namespace api\services\wechat;

use api\utils\LogUtil;
use Exception;
use Yii;

class WechatCp implements WechatInterface
{
    const ACCESS_TOKEN_PATH = '/gettoken';
    const JS_TICKET_PATH = '/get_jsapi_ticket';

    public $corpId;
    public $host;
    public $apps;

    public function __construct()
    {
        $this->corpId = Yii::$app->params['zw']['corpid'];
        $this->host = Yii::$app->params['zw']['host'];
        $this->apps = Yii::$app->params['zw']['apps'];
    }

    public function getJsTicketAppId()
    {
        return $this->corpId;
    }

    public function getHost()
    {
        return $this->host;
    }

    public function getJsTicketUrl($access_token)
    {
        return $this->host .  self::JS_TICKET_PATH . '?access_token=' . $access_token;
    }

    public function getAccessTokenUrl($app = '')
    {
        $config = $this->apps[$app];
        if (empty($config)) {
            throw new Exception('该应用不存在: ' . $app);
        }
        return $this->host .  self::ACCESS_TOKEN_PATH . '?corpid=' . $this->corpId . '&corpsecret=' . $config['secret'];
    }

    public function getWechatUser($access_token, $code)
    {
        $url = $this->host . "/user/getuserinfo?access_token={$access_token}&code={$code}";
        $response = Yii::$app->curl->get($url);
        if (empty($response['UserId'])) {
            LogUtil::warn(['message' => 'get Wecaht user info error', 'response' => $response], 'wechat-error');
            throw new Exception('获取政务微信用户失败');
        }

        return $response['UserId'];
    }

    /**
     * @see https://wx.sh.gov.cn/api/doc#10167/%E6%96%87%E6%9C%AC%E5%8D%A1%E7%89%87%E6%B6%88%E6%81%AF
     *
     * @param [type] $access_token
     * @param array $userIds 成员ID列表（消息接收者，多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为@all，则向关注该单位应用的全部成员发送
     * @param [type] $params
     * @return void
     */
    public function sendMessage($appKey, $userIds, $params, $access_token)
    {
        // {
        //     "touser" : "UserID1|UserID2|UserID3",
        //     "toparty" : " PartyID1 | PartyID2 ",
        //     "totag" : " TagID1 | TagID2 ",
        //     "msgtype" : "textcard",
        //     "agentid" : 1,
        //     "textcard" : {
        //              "title" : "领奖通知",
        //              "description" : "<div class=\"gray\">2016年9月26日</div> <div class=\"normal\">恭喜你抽中iPhone 7一台，领奖码：xxxx</div><div class=\"highlight\">请于2016年10月10日前联系行政同事领取</div>",
        //              "url" : "URL"
        //     }
        //  }
        $textcard = [
            'title' => $params['title'],
            'description' => $params['description'],
            'url' => $params['url'],
        ];
        $appConfig = $this->apps[$appKey];
        $sendParams = [
            'msgtype' => 'textcard',
            'touser' => implode('|', $userIds),
            'agentid' => $appConfig['agentId'],
            'textcard' => $textcard,
        ];
        $url = $this->host . "message/send?access_token={$access_token}";

        $response = Yii::$app->curl->post($url, $sendParams);
        LogUtil::warn(['message' => 'send wechat message', 'response' => $response]);
        return $response;
    }
}
